package com.glorysoft.wangnianxinpda.activity;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;

import android.Manifest;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;

import com.glorysoft.wangnianxinpda.R;
import com.glorysoft.wangnianxinpda.base.App;
import com.glorysoft.wangnianxinpda.base.BaseActivity;
import com.glorysoft.wangnianxinpda.base.Constant;
import com.glorysoft.wangnianxinpda.entity.LoginEntity;
import com.glorysoft.wangnianxinpda.entity.net.ResponseEntity;
import com.glorysoft.wangnianxinpda.databinding.ActivityLoginBinding;
import com.glorysoft.wangnianxinpda.utils.GsonUtils;
import com.glorysoft.wangnianxinpda.utils.MyUtils;
import com.glorysoft.wangnianxinpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_NetUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.glorysoft.wangnianxinpda.base.Constant.loginEntity;
import static com.glorysoft.wangnianxinpda.utils.MD5Utils.stringToMD5;

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private ActivityLoginBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return 0;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
        String[] arrayof = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE};
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
         ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < arrayof.length; i++) {
            if (ActivityCompat.checkSelfPermission(this, arrayof[i]) != PackageManager.PERMISSION_GRANTED) {
                list.add(arrayof[i]);
            }
        }

        if (list.size() > 0) {
            ActivityCompat.requestPermissions(this, list.toArray(new String[list.size()]), 0);
        } else {
            showToast("授权成功", true);
        }

        binding.ivSetting.setOnClickListener(this);
        binding.btnLogin.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        //删除日志
        FreeApi_Utils.deleteLog();
        detectionUpdate();
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return null;
    }

    @Override
    public void onClick(View v) {
        if (new MyUtils().isFastClick()) {
            showToast("您点击的太快了", false);
        }

        int id = v.getId();
        if (id == R.id.ivSetting) {
            FreeApi_Utils.skipWithExtraIntent(
                    "header",
                    this,
                    SettingActivity.class);
        } else if (id == R.id.btnLogin) {
            String workNo = "";
            if (binding.etMobile.getText().toString().trim().isEmpty()) {
                workNo = binding.etMobile.getText().toString().trim();
                showToast("请输入用户名", false);
                return;
            }
            if (binding.etPassword.getText().toString().trim().isEmpty()) {
                showToast("请输入密码", false);
                return;
            }

            requestLogin();
//            loginEntity.setWORK_NO(binding.etMobile.getText().toString().trim());
//            FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, HomeActivity.class);
//            finish();

        }

    }

    //region 接口调用
    private void requestLogin() {
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "LOGIN");
        map.addProperty("WORK_NO", binding.etMobile.getText().toString().trim());
        map.addProperty("PASSWORD", binding.etPassword.getText().toString().trim());

        NetUtils.requestPostNet("", "PDALogin", this, map, new FreeUI_DialogEntityCallBack<ResponseEntity<LoginEntity>>(
                new TypeToken<ResponseEntity<LoginEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<LoginEntity>> response) {
                if (response.body().isSuccess(true, getSupportFragmentManager())) {
                    showToast("登录成功", true);
                    loginEntity = response.body().getData();
                    loginEntity.setWORK_NO(binding.etMobile.getText().toString().trim());
                    FreeApi_Utils.skipWithExtraIntent("", LoginActivity.this, HomeActivity.class);
                    finish();
                }
            }

            @Override
            public void onError(Response<ResponseEntity<LoginEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDALogin");
            }
        });
    }

    //endregion


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
//        App.IMEI_ID = telephonyManager.getDeviceId();
//        if (App.IMEI_ID == null) {
//            App.IMEI_ID = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
//        }
    }

    private void detectionUpdate()
    {
        PackageManager manager = getPackageManager();
        PackageInfo info = null;
        try {
            info = manager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = info.versionName;
        FreeUI_EntityCallBack<FreeUI_VersionEntity> callBack = new FreeUI_EntityCallBack<FreeUI_VersionEntity>
                (new TypeToken<FreeUI_VersionEntity>() {
                }.getType()) {

            @Override
            public void onSuccess(Response<FreeUI_VersionEntity> response) {
                FreeUI_VersionEntity entity = response.body();
                entity.setCurrentVersion(version);
                int code  = FreeApi_Utils.compareVersion(version,entity.getVersion());
                if(code == -1)
                {
                    FreeUI_DownloadFragmentDialog downloadFragmentDialog = new FreeUI_DownloadFragmentDialog();
                    downloadFragmentDialog.setData(entity);
                    downloadFragmentDialog.show(getSupportFragmentManager(),"DOWNLOAD");
                }
            }

            @Override
            public void onError
                    (Response<FreeUI_VersionEntity> response) {
                super.onError(response);
            }
        };
        Map<String, String> map = new HashMap<>();
        FreeApi_NetUtils.requestGetNet(Constant.FILE_URL+"/Version.txt", this, map, callBack);
    }

}